/*
 * Copyright 2007-2009 Thomas Krause (thomas@berlin-reloaded.de)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gidoo.cms.extra.wymeditor;

import org.apache.wicket.RequestCycle;
import org.apache.wicket.ResourceReference;
import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.model.Model;
import org.gidoo.cms.editor.edit.EditorComponent;

/**
 * An editor component using the wymeditor ("What you mean editor") which produces
 * valid XHTML. Please note that the editor needs a style file for a full operation.
 * By default it uses "style.css" in the Webapp root folder but you can override
 * this ({@link #getStyleFileRef() }).
 *
 * @author <a href="mailto:thomas@berlin-reloaded.de">Thomas Krause</a>
 */
public class WYMEditorComponent extends EditorComponent
{

  private TextArea<String> txtText;

  public WYMEditorComponent()
  {
    String styleFileRef = getStyleFileRef();
    if(!styleFileRef.startsWith("http://") && !styleFileRef.startsWith("https://") &&
			!styleFileRef.startsWith("/"))
		{
      styleFileRef =
        RequestCycle.get()
        .getProcessor()
        .getRequestCodingStrategy()
        .rewriteStaticRelativeUrl(styleFileRef);
		}

    final String styleFileRefFinal = styleFileRef;

    txtText = new TextArea<String>("txtText", new Model<String>(""));
    txtText.setOutputMarkupId(true);

    txtText.add(new AbstractDefaultAjaxBehavior()
    {

      @Override
      protected void respond(AjaxRequestTarget target)
      {
      }

      @Override
      public void renderHead(IHeaderResponse response)
      {
        super.renderHead(response);
        response.renderJavascriptReference(new ResourceReference(WYMEditorComponent.class,
          "jquery/jquery.js"));
        response.renderJavascriptReference(new ResourceReference(WYMEditorComponent.class,
          "wymeditor/jquery.wymeditor.pack.js"));
        response.renderOnDomReadyJavascript(
          "$('.wymeditor').wymeditor({\n" +
          "updateSelector: '.cmsEditorSubmitElement',\n" +
            (styleFileRefFinal == null ? "" : ("stylesheet: '" + styleFileRefFinal + "'")) + ",\n" +
          "toolsItems: [ \n" +
        "{'name': 'Bold', 'title': 'Strong', 'css': 'wym_tools_strong'}\n, " +
        "{'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis'},\n " +
        "{'name': 'Superscript', 'title': 'Superscript', \n" +
        "    'css': 'wym_tools_superscript'}, \n" +
        "{'name': 'Subscript', 'title': 'Subscript',\n" +
        "    'css': 'wym_tools_subscript'}, \n" +
        "{'name': 'InsertOrderedList', 'title': 'Ordered_List',\n" +
        "    'css': 'wym_tools_ordered_list'},\n" +
        "{'name': 'InsertUnorderedList', 'title': 'Unordered_List',\n" +
        "    'css': 'wym_tools_unordered_list'},\n" +
        "{'name': 'Indent', 'title': 'Indent', 'css': 'wym_tools_indent'},\n" +
        "{'name': 'Outdent', 'title': 'Outdent', 'css': 'wym_tools_outdent'},\n" +
        "{'name': 'Undo', 'title': 'Undo', 'css': 'wym_tools_undo'},\n" +
        "{'name': 'Redo', 'title': 'Redo', 'css': 'wym_tools_redo'},\n" +
        "{'name': 'CreateLink', 'title': 'Link', 'css': 'wym_tools_link'},\n" +
        "{'name': 'Unlink', 'title': 'Unlink', 'css': 'wym_tools_unlink'},\n" +
        "{'name': 'InsertImage', 'title': 'Image', 'css': 'wym_tools_image'},\n" +
        "{'name': 'InsertTable', 'title': 'Table', 'css': 'wym_tools_table'},\n" +
        "{'name': 'Paste', 'title': 'Paste_From_Word',\n" +
        "    'css': 'wym_tools_paste'},\n" +
        "{'name': 'ToggleHtml', 'title': 'HTML', 'css': 'wym_tools_html'},\n" +
        "],\n" +
        "});");
      }
      
    });
    
    add(txtText);
    
  }

  @Override
  public String getText()
  {
    String s = txtText.getModelObject();
    if(s == null || "".equals(s))
    {
      return s;
    }
    else
    {
      return
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
        "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
        "<head><title></title></head>\n" +
        "<body>\n" + s + "\n</body>\n</html>";
    }
    
  }

  @Override
  public void setText(String newText)
  {
    txtText.setModelObject(newText);
  }

  @Override
  public boolean isPreviewFunctionNeeded()
  {
    return true;
  }

  @Override
  public void enableComponents(boolean enable)
  {
    txtText.setEnabled(enable);
  }

  @Override
  public String getDefaultXml()
  {
    return 
      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
      "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
      "<head><title></title></head>\n" +
      "<body>\n</body>\n</html>";
  }

  @Override
  public String getJavaScriptBeforeSubmit()
  {
    return "$('.cmsEditorSubmitElement').triggerHandler('click');";
  }

  /** Return a reference to where the style-file should be located */
  public String getStyleFileRef()
  {
    return "style.css";
  }
}
